﻿using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Windows;
using System.Windows.Controls;

namespace GenUI.WPF.GenControls
{
    internal class ExcelPage : Control
    {
        public Pager<DataRow> Pager { get; set; }
        private PagerBar PagerBar;
        private DataGrid DG;

        public DataTable Source
        {
            get { return (DataTable)GetValue(SourceProperty); }
            set { SetValue(SourceProperty, value); }
        }

        // Using a DependencyProperty as the backing store for Source.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty SourceProperty =
            DependencyProperty.Register("Source", typeof(DataTable), typeof(ExcelPage), new PropertyMetadata(null, OnSourceChanged));

        private static void OnSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is ExcelPage EP && EP.DG != null && e.NewValue != null)
            {
                EP.Refresh(EP, (DataTable)e.NewValue);
            }
        }
        static ExcelPage()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(ExcelPage), new FrameworkPropertyMetadata(typeof(ExcelPage)));
        }
        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
            this.DG = GetTemplateChild("PART_Grid") as DataGrid;
            this.PagerBar = GetTemplateChild("PART_Pager") as PagerBar;
            Refresh(this,this.Source);
        }

        private void Refresh(ExcelPage Ep,DataTable source)
        {
            Ep.Pager = new Pager<DataRow>(8, source.Rows.Cast<DataRow>());
            Ep.Pager.PagerUpdated += items =>
            {
                DataTable dt = Ep.Source.Clone();
                foreach (var item in items)
                {
                    dt.ImportRow(item);
                }
                Ep.DG.ItemsSource = dt.AsDataView();
            };
            Ep.Pager.CurPageIndex = 1;
            Ep.PagerBar.DataContext = Ep.Pager;
        }
    }
}
